package com.itboye.eweilisten.app;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.itboye.eweilisten.util.sputil.Const;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by admin on 2017/1/13.
 */

public class MyApplication extends Application {

    private List<WeakReference<Activity>> activityList = new LinkedList<>();

    public static MyApplication instance;
    public static Context context;
    private static RequestQueue queue;
    public IWXAPI api;
    public static MyApplication getInstance() {
        return instance;
    }

    public PushAgent mPushAgent;

    public PushAgent getmPushAgent() {
        return mPushAgent;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        api = WXAPIFactory.createWXAPI(this, null);
        api.registerApp(Const.APP_ID);
        instance = this;

        context = getApplicationContext();

        queue = Volley.newRequestQueue(this);

        initUMengPush();
    }

    private void initUMengPush() {
        mPushAgent = PushAgent.getInstance(this);
        mPushAgent.setDebugMode(true);
        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            /**
             * 自定义消息的回调方法
             * */
            @Override
            public void dealWithCustomMessage(final Context context,
                                              final UMessage msg) {
                new Handler().post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        // 对自定义消息的处理方式，点击或者忽略
                        boolean isClickOrDismissed = true;
                        if (isClickOrDismissed) {
                            // 自定义消息的点击统计
                            UTrack.getInstance(getApplicationContext())
                                    .trackMsgClick(msg);
                        } else {
                            // 自定义消息的忽略统计
                            UTrack.getInstance(getApplicationContext())
                                    .trackMsgDismissed(msg);
                        }
                        Toast.makeText(context, msg.custom, Toast.LENGTH_LONG)
                                .show();
                    }
                });
            }

            @Override
            public void dealWithNotificationMessage(Context arg0, UMessage arg1) {
                // TODO Auto-generated method stub
                super.dealWithNotificationMessage(arg0, arg1);
            }

//            /**
//             * 自定义通知栏样式的回调方法
//             * */
//            @SuppressLint("NewApi")
//            @Override
//            public Notification getNotification(Context context, UMessage msg) {
//                switch (msg.builder_id) {
//                    case 1:
//                        Notification.Builder builder = new Notification.Builder(
//                                context);
//                        RemoteViews myNotificationView = new RemoteViews(
//                                context.getPackageName(),
//                                R.layout.notification_view);
//                        myNotificationView.setTextViewText(R.id.notification_title,
//                                msg.title);
//                        myNotificationView.setTextViewText(R.id.notification_text,
//                                msg.text);
//                        myNotificationView.setImageViewBitmap(
//                                R.id.notification_large_icon,
//                                getLargeIcon(context, msg));
//                        myNotificationView.setImageViewResource(
//                                R.id.notification_small_icon,
//                                getSmallIconId(context, msg));
//                        builder.setContent(myNotificationView)
//                                .setSmallIcon(getSmallIconId(context, msg))
//                                .setTicker(msg.ticker).setAutoCancel(true);
//
//                        return builder.getNotification();
//                    default:
//                        // 默认为0，若填写的builder_id并不存在，也使用默认。
//                        return super.getNotification(context, msg);
//                }
//            }
        };
//        mPushAgent.setMessageHandler(messageHandler);

        /**
         * 自定义行为的回调处理 UmengNotificationClickHandler是在BroadcastReceiver中被调用，故
         * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
         * */
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {

            }

            @Override
            public void openActivity(Context arg0, UMessage arg1) {
                // TODO Auto-generated method stub
                // super.openActivity(arg0, arg1);//必须注释掉才能执行指定类的跳转
//                Gson gson = new Gson();
//                NotificationBean bean = gson.fromJson(arg1.getRaw().toString(),
//                        NotificationBean.class);
//                Intent intent = new Intent();
//                String uid = SPUtils.get(ctx, null, SPContants.USER_ID, "")
//                        + "";
//                if (uid.equals("")) {
//                    intent = new Intent(ctx, LoginActivity.class);
//                    startActivity(intent);
//                    return;
//                }
//                if (bean.getBody().getActivity().equals("system_message")) {
//                    intent = new Intent(ctx, ActivitySystemMessage.class);
//                    intent.putExtra("type", 1);
//                } else if (bean.getBody().getActivity()
//                        .equals("contract_message")) {
//                    intent = new Intent(ctx, ActivityMySign.class);
//                    intent.putExtra("contract_no", bean.getExtra().getId());
//                    Intent intent1 = new Intent(OrderFragment.REFRESH);
//                    sendBroadcast(intent1);
//                } else if (bean.getBody().getActivity().equals("lock_message")) {
//                    intent = new Intent(ctx, ActivitySystemMessage.class);
//                    intent.putExtra("type", 4);
//                } else if (bean.getBody().getActivity().equals("wallet_message")) {
//                    intent = new Intent(ctx, ActivityMyWallte.class);
//                    intent.putExtra("type", 5);
//                } else if (bean.getBody().getActivity().equals("rent_message")) {
//                    //intent = new Intent(ctx, WodeFangyuanActivity.class);
//                    intent = new Intent(ctx, ActivityXuanZuKe.class);
//                    intent.putExtra("house_no", bean.getExtra().getHouse_no());
//                }
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
            }
        };
        // 使用自定义的NotificationHandler，来结合友盟统计处理消息通知
        // 参考http://bbs.umeng.com/thread-11112-1-1.html
        // CustomNotificationHandler notificationClickHandler = new
        // CustomNotificationHandler();
        mPushAgent.setNotificationClickHandler(notificationClickHandler);

        // 注册推送服务 每次调用register都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                System.out.println(">>>deviceToken" + deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                System.out.println(">>>deviceToken--onFailure" + s + "s1"+s1);

            }
        });
    }

    public void addActivity(Activity activity) {
        activityList.add(new WeakReference<Activity>(activity));
    }

    /**
     * @return the queue
     */
    public static RequestQueue getQueue() {
        return queue;
    }

    //
    public static <T> void addRequest(Request<T> request) {
        request.addMarker("itboye");
        getQueue().add(request);
    }
}
